﻿using FolderTag.DB.Dbo;
using FolderTag.Model;
using System.Collections.Generic;
using System.Linq;

namespace FolderTag.DB
{
    /// <summary>
    /// 目录TagDb类
    /// </summary>
    public static class FolderTagDb
    {
        private static object _LockObject = new object();

        private static List<TagItem> _TagList = null;
        /// <summary>
        /// 添加Tag
        /// </summary>
        /// <param name="tagName"></param>
        public static bool Add(TagItem tagItem)
        {
            return DBHelper.SQL_R.Insert(FolderTagDbo.CreateNew(tagItem), false) > 0;
        }
        /// <summary>
        /// 更新Tag
        /// </summary>
        /// <param name="tagItem"></param>
        /// <returns></returns>

        public static bool Update(TagItem tagItem)
        {
            return DBHelper.SQL_R.Update(FolderTagDbo.Create(tagItem)) > 0;
        }

        /// <summary>
        /// 删除Tag
        /// </summary>
        /// <param name="id"></param>
        public static bool Delete(int id)
        {
            return DBHelper.SQL_R.Delete<FolderTagDbo>(id) > 0;
        }

        /// <summary>
        /// 根据编号批量获取
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public static List<TagItem> GetByIds(HashSet<int> ids)
        {
            return QueryList().Where(x => ids.Contains(x.Id)).ToList();
        }

        /// <summary>
        /// 根据名称获取Tag
        /// </summary>
        /// <param name="tagName"></param>
        /// <returns></returns>
        public static TagItem GetByName(string tagName)
        {
            return QueryList().Where(x => x.Name.Equals(tagName)).FirstOrDefault();
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <returns></returns>
        public static List<TagItem> QueryList(bool isRefresh = false)
        {
            if (_TagList == null || isRefresh)
            {
                lock (_LockObject)
                {
                    if (_TagList == null || isRefresh)
                        _TagList = DBHelper.SQL_R.FindList<FolderTagDbo>().Select(x => new TagItem(x)).ToList();

                }
            }
            return _TagList ?? new List<TagItem>();
        }
    }
}
